from time import sleep

import requests

from operator import itemgetter
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

#执行api调用并响应存储
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print("Status code:",r.status_code)
#处理有关每篇文章的信息
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:5]:
    #对于每篇文章，都执行一个api调用
    url = ('https://hacker-news.firebaseio.com/v0/item/' +
           str(submission_id) + '.json')
    submission_r = requests.get(url)
    print(submission_r.json())
    response_dict = submission_r.json()

    submission_dict = {
        'comments': int(response_dict['descendants']),
        'title': response_dict['title'],
        'link': 'http://news.ycombinator.com/item?id=' + str(submission_id),
    }
    submission_dicts.append(submission_dict)
    sleep(1)
submission_dicts = sorted(submission_dicts, key=itemgetter('comments'),
                        reverse=True)
titles = []

for submission_dict in submission_dicts:
    print("\nTitle:", submission_dict['title'])
    print("Discussion link:", submission_dict['link'])
    print("Comments:", submission_dict['comments'])
    titles.append(submission_dict['title'])

my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'hacker-news'
chart.x_labels = titles
plot_dicts = []
for submission_dict in submission_dicts:
    values = submission_dict['comments']
    plot_dict = {'value': values, 'xlink': submission_dict['link']}
    plot_dicts.append(plot_dict)
chart.add('', plot_dicts)
chart.render_to_file('bar_hacker_news.svg')